import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  ListView,
  Image,
  Switch,
  Dimensions,
  Text,
  TouchableOpacity,
  ScrollView,
  PanResponder,
} from 'react-native'
import NavigationBar from '../../components/common/NavigationBar'
import IconModel from '../../components/common/IconModel'
import { BoxShadow } from 'react-native-shadow'

const { width, height } = Dimensions.get('window')
let BG_HEIGHT = 340
let BG_WIDTH = 162
let RADIUS = 48
let _previousTop = 0
let _previousWidth = 0
let _bottomRadius = 0

let lastTop = 0

class RollerBlind extends Component {
  constructor(props) {
    super(props)
    this.state = {
      iconModelList: [
        {
          icon: 'icon_chuanglian_kai',
          name: '开窗帘',
          color: '#669CE5',
        },
        {
          icon: 'icon_chuanglian_guan',
          name: '关窗帘',
          color: '#676767'
        },
        {
          icon: 'icon_chuanglian_stop',
          name: '暂停',
          color: '#F2736D'
        }
      ],
      switchValue: false,
      openDegree: 0,
      openDegreeStyle: {
        height: 0,
        width: 0,
        borderBottomLeftRadius: 0,
        borderBottomRightRadius: 0,
      },
      btnStyle: {marginTop: 0,},
    }
    this.dataSource = new ListView.DataSource({
      rowHasChanged: ((row1, row2) => row1 !== row2)
    })
    this.onStartShouldSetPanResponder = this.onStartShouldSetPanResponder.bind(this);
    this.onMoveShouldSetPanResponder = this.onMoveShouldSetPanResponder.bind(this);
    this.onPanResponderGrant = this.onPanResponderGrant.bind(this);
    this.onPanResponderMove = this.onPanResponderMove.bind(this);
    this.onPanResponderRelease = this.onPanResponderRelease.bind(this);
  }
  componentWillMount(evt, gestureState) {

    this._panResponder = PanResponder.create({
      //用户开始触摸屏幕的时候，是否愿意成为响应者；默认返回false，无法响应，
      // 当返回true的时候则可以进行之后的事件传递。
      onStartShouldSetPanResponder: this.onStartShouldSetPanResponder,

      //在每一个触摸点开始移动的时候，再询问一次是否响应触摸交互；
      onMoveShouldSetPanResponder: this.onMoveShouldSetPanResponder,

      //开始手势操作，也可以说按下去。给用户一些视觉反馈，让他们知道发生了什么事情！（如：可以修改颜色）
      onPanResponderGrant: this.onPanResponderGrant,

      //最近一次的移动距离.如:(获取x轴y轴方向的移动距离 gestureState.dx,gestureState.dy)
      onPanResponderMove: this.onPanResponderMove,

      //用户放开了所有的触摸点，且此时视图已经成为了响应者。
      onPanResponderRelease: this.onPanResponderRelease,

      //另一个组件已经成为了新的响应者，所以当前手势将被取消。
      onPanResponderTerminate: this.onPanResponderEnd,
    });
  }
  //用户开始触摸屏幕的时候，是否愿意成为响应者；
  onStartShouldSetPanResponder(evt, gestureState) {
    return true;
  }

  //在每一个触摸点开始移动的时候，再询问一次是否响应触摸交互；
  onMoveShouldSetPanResponder(evt, gestureState) {
    return true;
  }

  // 开始手势操作。给用户一些视觉反馈，让他们知道发生了什么事情！
  onPanResponderGrant(evt, gestureState) {
    console.log(parseInt(_previousTop/BG_HEIGHT));
  }

  // 最近一次的移动距离为gestureState.move{X,Y}
  onPanResponderMove(evt, gestureState) {
    console.log(gestureState)
    _previousTop = lastTop + gestureState.dy;

    //主要是限制小球拖拽移动的时候不许出屏幕外部
    if (_previousTop <= 0) {
      _previousTop = 0
    }

    if (_previousTop >= BG_HEIGHT) {
      _previousTop = BG_HEIGHT
    }

    _previousWidth = BG_WIDTH


    if (_previousTop >= 0 && _previousTop <= RADIUS ) {
      let z = Math.sqrt(Math.pow(RADIUS, 2) - Math.pow((RADIUS - _previousTop),2))
      _previousWidth = BG_WIDTH - RADIUS * 2 + z * 2
      _bottomRadius = RADIUS - _previousTop
    }

    if (_previousTop >= (BG_HEIGHT - RADIUS) && _previousTop <= BG_HEIGHT) {
      _bottomRadius = RADIUS - (BG_HEIGHT - _previousTop)
    }else{
      _bottomRadius = 0
    }

    console.log(_bottomRadius)

    //实时更新
    this.setState({
      openDegreeStyle: {
        height: _previousTop,
        width: _previousWidth,
        borderBottomLeftRadius: _bottomRadius,
        borderBottomRightRadius: _bottomRadius
      },
      btnStyle: {
        marginTop: _previousTop,
      },
      openDegree: parseInt(_previousTop/BG_HEIGHT*100)
    });
  }

  // 用户放开了所有的触摸点，且此时视图已经成为了响应者。
  // 一般来说这意味着一个手势操作已经成功完成。
  onPanResponderRelease(evt, gestureState) {
    console.log(gestureState)
    lastTop = _previousTop
  }
  render() {

    return (
      <View style = {styles.container}>
        <NavigationBar
          title={'卷帘'}
          statusBar={{backgroundColor: '#F4F4F4', barStyle: 'dark-content'}}
          style={{backgroundColor: '#F4F4F4'}}
          navigator={this.props.navigator}
        />
        <ScrollView contentContainerStyle={styles.contentContainer} showsVerticalScrollIndicator={false}>
          <View>
            <Text style={styles.title}>开合度</Text>
            <View style={styles.svgView}>
              <View style={styles.bgView}>
                <View style={[styles.openContent, this.state.openDegreeStyle]}></View>
              </View>
              <View style={styles.btnView}>
                <View style={[styles.btn, this.state.btnStyle]} {...this._panResponder.panHandlers}>
                  <TouchableOpacity>
                    <Image style={{width: 42, height: 42,}} source={require('../../img/btn_33.png')}/>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
            <Text style={styles.svgValue}>{this.state.openDegree}%</Text>
          </View>
          <View style={[styles.operation, styles.flex]}>
            {this._renderList(this.state.iconModelList)}
          </View>
          <View style={styles.modelList}>
            <BoxShadow setting={this._getShadowOpt({
                width: width - 30,
                height: 94,
                style: {marginTop: 10}
              })}>
              <View style={styles.power}>
                <View style={styles.flex}>
                  <Text style={styles.powerText}>指令反向</Text>
                  <Switch
                    style={styles.powerSwitch}
                    value={this.state.switchValue}
                    onTintColor='#00A5AD'
                    tintColor='#999999'
                    thumbTintColor='#ffffff'
                    onValueChange={
                      (value)=>{
                        this.setState({
                          switchValue:value
                        })
                      }
                    }
                  />
                </View>
                <Text style={styles.info}>开启此选项后，场景模式指令将会按反向状态</Text>
              </View>
            </BoxShadow>
          </View>
        </ScrollView>
      </View>
    )
  }
  _renderList(list) {
    return list.map( item => this._renderItem(item) );
  }
  _renderItem(item) {
    return (
      <IconModel
        width={100}
        height={100}
        fontSize={13}
        iconSize={48}
        icon={item.icon}
        name={item.name}
        color={item.color}
      />
    )
  }
  _getShadowOpt(data) {
    return {
      width: data.width,
      height: data.height,
      color: "#999999",
      border: 2,
      radius: 6,
      opacity: 0.1,
      x: 0,
      y: 2,
      style: data.style
    }
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#F4F4F4'
  },
  contentContainer: {
    marginBottom: 20,
  },
  title: {
    color: '#333333',
    fontSize: 14,
    marginTop: 15,
    marginLeft: 35,
    fontWeight: 'bold',
  },
  svgView: {
    paddingTop: 21,
    paddingBottom: 21,
    alignItems: 'center',
    position: 'relative',
  },
  bgView: {
    width: 162,
    height: 340,
    backgroundColor: '#ffffff',
    borderRadius: RADIUS,
    alignItems: 'center',
  },
  openContent: {
    backgroundColor: '#00A5AD',
    borderTopLeftRadius: RADIUS,
    borderTopRightRadius: RADIUS,
  },
  btnView: {
    position: 'absolute',
    top: 2,
    height: 378,
    width: 42,
  },
  btn: {
    width: 42,
    height: 42,
  },
  svgValue: {
    textAlign: 'center',
    fontSize: 24,
    color: '#666666',
    marginBottom: 20,
  },
  operation: {
    width: width - 30,
    marginLeft: 15,
  },
  modelList: {
    marginBottom: 30,
    marginLeft: 15,
  },
  flex: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  power: {
    height: 94,
    width: width - 30,
    backgroundColor: '#fff',
    borderRadius: 6,
    paddingLeft: 20,
    paddingRight: 20,
    justifyContent: 'center',
  },
  powerText: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#333333',
  },
  powerSwitch: {
  },
  info: {
    color: '#666666',
    fontSize: 13,
    marginTop: 14,
  }
})

export default RollerBlind
